from fastapi.responses import JSONResponse
from typing import Optional
from argon2 import PasswordHasher, exceptions
from fastapi import APIRouter,Depends,Form
from User import models,schemas
from User.database import SessionLocal
from sqlalchemy.orm import Session

from User.models import User

router = APIRouter()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()




ph = PasswordHasher()


@router.post("/login")
async def login(username: str , password: str , autoLogin: bool , type: str = "account", db: Session = Depends(get_db)):
    if type == "account":
        user = db.query(User).filter(User.username == username).first()
        if not user:
            return JSONResponse(content={"status": "error", "type": "account", "message": "Invalid username or password."})
        try:
            if ph.verify(user.password, password):
                return JSONResponse(content={"status": "ok", "type": "account", "currentAuthority": "admin"})
            else:
                return JSONResponse(content={"status":"error","type":"account","currentAuthority":"guest"})
        except exceptions.VerifyMismatchError:
            return JSONResponse(content={"status": "error", "type": "account", "message": "Invalid username or password."})
        except exceptions.ExpiredHashError:
            return JSONResponse(content={"status": "error", "type": "account", "message": "Expired hash."})
        except exceptions.InvalidHash:
            return JSONResponse(content={"status": "error", "type": "account", "message": "Invalid hash."})


@router.delete('/delete')
def del_user(usename:str,db: Session = Depends(get_db)):
    db.query(models.User).filter(models.User.username == usename).delete(synchronize_session=False)
    db.commit()
    return {"msg": "已经删除"}


@router.post("/create")
async def create_user(username: str = Form(...), password: str = Form(...), email: Optional[str] = Form(None), db: Session = Depends(get_db)):
    new_user = User(username=username, password=ph.hash(password.encode()), email=email)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return JSONResponse(content={"status": "ok", "data": {"id": new_user.id}})


@router.get("/currentUser")
async def get_current_user():
    current_user = {"name": "Serati Ma", "avatar": "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png", "userid": "00000001", "email": "antdesign@alipay.com", "signature": "海纳百川，有容乃大", "title": "交互专家", "group": "蚂蚁金服－某某某事业群－某某平台部－某某技术部－UED", "tags": [{"key": "0", "label": "很有想法的"}, {"key": "1", "label": "专注设计"}, {"key": "2", "label": "辣~"}, {"key": "3", "label": "大长腿"}, {"key": "4", "label": "川妹子"}, {"key": "5", "label": "海纳百川"}], "notifyCount": 12, "unreadCount": 11, "country": "China", "access": "admin", "geographic": {"province": {"label": "浙江省", "key": "330000"}, "city": {"label": "杭州市", "key": "330100"}}, "address": "西湖区工专路 77 号", "phone": "0752-268888888"}

    #current_user = {"name": "Admin", "avatar": "https://xsgames.co/randomusers/avatar.php?g=pixel", "userid": "00000001", "email": "lhzhao2023@163.com", "notifyCount": 12, "unreadCount": 11, "signature": "海纳百川，有容乃大", "title": "journal", "group": "蚂蚁金服－某某某事业群－某某平台部－某某技术部－UED", "tags": [{"key": "0", "label": "很有想法的"}, {"key": "1", "label": "专注设计"}], "country": "China", "access": "admin", "geographic": {"province": {"label": "江苏省", "key": "330000"}, "city": {"label": "苏州市", "key": "330100"}}, "address": "苏州大学东校区", "phone": "0752-268888888"}
    return {"success": False, "data": []}


@router.post("/outLogin")
async def login_out():
    return {"data":{},"success":True}


@router.get("/get")
def read_users(db: Session = Depends(get_db)):
    users = db.query(models.User).all()
    return users